package com.migu.rbac.service;

import com.migu.rbac.message.RbacMessageService;
import com.migu.rbac.model.SysUser;
import com.migu.rbac.repository.SysUserRepository;
import com.migu.rbac.repository.SysUserRoleRepository;
import com.migu.rbac.util.CheckPassword;
import com.migu.rbac.util.MD5Util;
import com.migu.rbac.vo.*;
import com.migu.rbac.vo.page.UserPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Description TODO :
 * @Author: zj
 * @Date: 9:59 2019/4/4
 * @Version 1.0
 **/
@Service
@Transactional
public class SysUserService {
    @Autowired
    SysUserRepository userRepository;

    @Autowired
    SysUserRoleRepository userRoleRepository;

    @Autowired
    private RbacMessageService rbacMessageService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${sendmessage.msg-pwd-template}")
    private String MSG_PWD_TEMPLATE;

    //根据登录名查找用户
    public SysUser findByloginName(String loginname) {
        return userRepository.findByloginName(loginname);
    }

    //根据用户id查询用户
    public SysUser findUserByUserId(Integer id) {
        return userRepository.findUserByUserId(id);
    }


    //新增用户
    public Boolean saveUser(SysUser sysUser) {
        SysUser byUsername = this.findByloginName(sysUser.getLoginname());
        if (byUsername != null) {
            return false;
        }
        String encodePwd = MD5Util.encode(sysUser.getPassword());
        sysUser.setPassword(encodePwd);
        if (userRepository.saveUser(sysUser) > 0) {
            return true;
        } else {
            return false;
        }
    }

    //修改用户信息
    public Boolean updateUser(SysUser sysUser) {
        if (userRepository.selectUserByUpdate(sysUser) > 0) {
            return false;
        }
        sysUser.setPassword(MD5Util.encode(sysUser.getPassword()));
        if (userRepository.updateUser(sysUser) > 0) {
            return true;
        } else {
            return false;
        }
    }

    //删除用户
    public Boolean deleteUser(int uid) {
        try {
            //删除用户下的角色
            userRoleRepository.deleteUserRole(uid);
            //删除用户
            userRepository.deleteUser(uid);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    //按条件查询所有用户 分页
    public PageInfoRespone selectUserByExample(UserPage userPage) {
        PageInfoRespone<SysUser> infoRespone = new PageInfoRespone<SysUser>();
        infoRespone.setCount(userRepository.selectCount(userPage));
        infoRespone.setPageNum(userPage.getPageNum());
        infoRespone.setPageSize(userPage.getPageSize());
        userPage.setPageNum((userPage.getPageNum() - 1) * userPage.getPageSize());
        List<SysUser> sysUsers = userRepository.selectUserByExample(userPage);
        infoRespone.setList(sysUsers);
        return infoRespone;
    }

    //保存其它的项目的数据到sys_user表
    public int savaFromOther(List<SysUser> sysUser) {
        //存在的用户不保存
        sysUser.removeIf(e -> userRepository.findByloginName(e.getLoginname()) != null);
        return userRepository.savaFromOther(sysUser);
    }

    //根据用户名删除用户
    public int deleteUserByLoginName(String loginname) {
        return userRepository.deleteUserByLoginName(loginname);
    }

    //根据用户名修改用户
    public int updateUserByLoginName(SysUser user) {
        if (!StringUtils.isEmpty(user.getPassword())) {
            user.setPassword(MD5Util.encode(user.getPassword()));
        }
        return userRepository.updateUserByLoginName(user);
    }

    public int saveUserFromEye(SysUser user) {
        return userRepository.saveUserFromEye(user);
    }

    /**
     * 修改用户密码
     *
     * @param loginName
     * @param phone
     * @param verification
     * @return
     */
    public Response updateUserPwdByUserInfo(String loginName, String phone, String password, String verification) {
        //验证验证码
        SysUser user = this.findByloginName(loginName);
        if (user == null) {
            return Response.error(ErrorCodes.LOGINNAME_NOT_EXIST.getCode(), ErrorCodes.LOGINNAME_NOT_EXIST.getDesc());
        }
        if (!user.getPhone().equals(phone)) {
            return Response.error(ErrorCodes.PHONENUMBER_NOT_EXIST.getCode(), ErrorCodes.PHONENUMBER_NOT_EXIST.getDesc());
        }
        StringBuffer msgKeys = new StringBuffer().append(user.getPhone()).append(user.getLoginname() + "pwd:");//验证码存储在redis中的key
        String msgValue = (String) redisTemplate.opsForValue().get(msgKeys.toString());
        if (!verification.equals(msgValue)) {
            return Response.error(ErrorCodes.VERIFICATION_WRONG.getCode(), ErrorCodes.VERIFICATION_WRONG.getDesc());
        }
        //删除key
        redisTemplate.delete(msgKeys.toString());
        Response check = CheckPassword.check(password, loginName);
        if (check.getCode() != Response.success().getCode()) {
            return check;
        }
        //MD5加密
        String encodePwd = MD5Util.encode(password);
        return Response.success(userRepository.updateUserPwdByUserInfo(loginName, phone, encodePwd));

    }

    //发送短信验证码修改密码
    public Response sendMessageForUpPwd(String loginName, String phone) {
        String phoneNumber = "";
        if (!StringUtils.isEmpty(loginName) && !StringUtils.isEmpty(phone)) {
            SysUser user = this.findByloginName(loginName);
            //判断用户是否存在
            if (user == null) {
                return Response.error(ErrorCodes.LOGINNAME_NOT_EXIST.getCode(), ErrorCodes.LOGINNAME_NOT_EXIST.getDesc());
            }
            //验证手机号是否正确
            if (user.getPhone().equals(phone)) {
                phoneNumber = phone;
            } else {
                return Response.error(ErrorCodes.PHONENUMBER_NOT_EXIST.getCode(), ErrorCodes.PHONENUMBER_NOT_EXIST.getDesc());
            }
        }
        MsgRes msgs = null;
        if (!StringUtils.isEmpty(phoneNumber)) {
            loginName = loginName + "pwd:";
            //发送验证吗
            try {
                msgs = rbacMessageService.sendMsg(phoneNumber, loginName, MSG_PWD_TEMPLATE);
                if (!("01").equals(msgs.getCode())) {
                    return Response.error(Integer.valueOf(msgs.getCode()), msgs.getMessage());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Response.success(msgs);
    }

    public List<SysUser> findAllList() {
        return userRepository.findAllList();
    }
}
